<template>
  <div class="app-container">
    <!-- 标签页切换 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabChange" type="border-card">
      <el-tab-pane label="服务器视频" name="server">
        <!-- 服务器视频查询表单 -->
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="90px">
          <el-form-item label="所属设备" prop="deviceId">
            <el-select
              v-model="queryParams.deviceId"
              placeholder="请选择所属设备"
              clearable
              filterable
              style="width: 240px"
            >
              <el-option v-for="device in deviceList" :key="device.deviceId" :label="device.deviceName" :value="device.deviceId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文件名称" prop="fileName">
            <el-input
              v-model="queryParams.fileName"
              placeholder="请输入文件名称"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 240px">
              <el-option label="正常" value="0"></el-option>
              <el-option label="已删除" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 服务器视频操作按钮 -->
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['monitor:video:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['monitor:video:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['monitor:video:remove']"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['monitor:video:export']"
            >导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <!-- 服务器视频表格 -->
        <el-table
          v-loading="loading"
          :data="videoList"
          @selection-change="handleSelectionChange"
          border
          stripe
          :header-cell-style="{background:'#f5f7fa',color:'#606266'}"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="视频编号" align="center" prop="videoId" width="100" />
          <el-table-column label="所属设备" align="center" prop="deviceName" min-width="120" :show-overflow-tooltip="true" />
          <el-table-column label="文件名称" align="center" prop="fileName" min-width="180" :show-overflow-tooltip="true" />
          <el-table-column label="视频时间段" align="center" min-width="280">
            <template slot-scope="scope">
              <el-tag size="medium">
                {{ parseTime(scope.row.startTime) }} 至 {{ parseTime(scope.row.endTime) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="文件大小" align="center" prop="fileSize" width="120">
            <template slot-scope="scope">
              {{ formatFileSize(scope.row.fileSize) }}
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="status" width="100">
            <template slot-scope="scope">
              <el-tag type="success" v-if="scope.row.status === '0'">正常</el-tag>
              <el-tag type="danger" v-if="scope.row.status === '1'">已删除</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="200">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-video-play"
                @click="handlePreview(scope.row)"
              >预览</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['monitor:video:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['monitor:video:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-tab-pane>
      
      <!-- 本地录像标签页 -->
      <el-tab-pane label="本地录像" name="local">
        <div v-if="!isIndexedDBSupported" class="db-warning">
          <i class="el-icon-warning"></i>
          <span>您的浏览器不支持IndexedDB，无法使用本地录像功能</span>
        </div>
        
        <template v-else>
          <!-- 本地录像查询表单 -->
          <el-form :model="localQueryParams" ref="localQueryForm" size="small" :inline="true" label-width="90px">
            <el-form-item label="所属设备" prop="deviceName">
              <el-select
                v-model="localQueryParams.deviceName"
                placeholder="请选择所属设备"
                clearable
                filterable
                style="width: 240px"
              >
                <el-option 
                  v-for="device in localDeviceList" 
                  :key="device.deviceName" 
                  :label="device.deviceName" 
                  :value="device.deviceName"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="文件名称" prop="fileName">
              <el-input
                v-model="localQueryParams.fileName"
                placeholder="请输入文件名称"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleLocalQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleLocalQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <!-- 本地录像操作按钮 -->
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-refresh"
                size="mini"
                @click="getLocalRecordings"
              >刷新列表</el-button>
            </el-col>
          </el-row>

          <!-- 本地录像表格 -->
          <el-table
            v-loading="localLoading"
            :data="filteredLocalRecordings"
            @selection-change="handleLocalSelectionChange"
            border
            stripe
            :header-cell-style="{background:'#f5f7fa',color:'#606266'}"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="所属设备" align="center" prop="deviceName" min-width="120" :show-overflow-tooltip="true" />
            <el-table-column label="文件名称" align="center" prop="fileName" min-width="180" :show-overflow-tooltip="true" />
            <el-table-column label="录制时间" align="center" prop="recordTime" min-width="180" :show-overflow-tooltip="true" />
            <el-table-column label="文件大小" align="center" prop="fileSize" width="120" />
            <el-table-column label="时长" align="center" prop="duration" width="120" />
            <el-table-column label="来源" align="center" width="100">
              <template slot-scope="scope">
                <el-tag type="info">本地录制</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="200">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-video-play"
                  @click="handlePreview(scope.row)"
                >预览</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-download"
                  @click="downloadLocalVideo(scope.row)"
                >下载</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-tab-pane>
    </el-tabs>

    <!-- 添加或修改监控视频对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body class="custom-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属设备" prop="deviceId">
          <el-select
            v-model="form.deviceId"
            placeholder="请选择所属设备"
            filterable
            style="width: 100%"
          >
            <el-option v-for="device in deviceList" :key="device.deviceId" :label="device.deviceName" :value="device.deviceId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文件名称" prop="fileName">
          <el-input v-model="form.fileName" placeholder="请输入文件名称" />
        </el-form-item>
        <el-form-item label="视频时间段" prop="timeRange">
          <el-date-picker
            v-model="timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%"
            @change="handleTimeRangeChange"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="存储路径" prop="filePath">
          <el-input v-model="form.filePath" placeholder="请输入存储路径">
            <template slot="prepend">/video/</template>
          </el-input>
        </el-form-item>
        <el-form-item label="文件大小" prop="fileSize">
          <el-input-number 
            v-model="form.fileSize" 
            :min="0" 
            :precision="2"
            :step="0.5"
            style="width: 100%"
            placeholder="请输入文件大小(MB)"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">已删除</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 视频预览对话框 -->
    <el-dialog 
      title="视频预览" 
      :visible.sync="previewOpen" 
      width="800px" 
      append-to-body 
      class="preview-dialog"
      :before-close="closeVideoPreview"
      destroy-on-close
    >
      <div class="video-container" v-loading="videoLoading" element-loading-text="视频加载中...">
        <video 
          v-if="previewUrl" 
          :src="previewUrl" 
          controls 
          class="video-player"
          preload="auto"
          ref="previewVideo"
          @canplay="handleVideoCanPlay"
          @error="handleVideoError"
        >
          <source :src="previewUrl" type="video/webm" />
          您的浏览器不支持 video 标签。
        </video>
        <div v-else-if="!videoLoading" class="no-video">
          <i class="el-icon-video-camera"></i>
          <p>暂无可预览的视频</p>
          <p v-if="isIndexedDBSupported" class="video-help-text">
            未找到对应的视频数据，请确认视频文件是否存在
          </p>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeVideoPreview">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listVideo, getVideo, delVideo, addVideo, updateVideo } from "@/api/newMonitor/video";
import { listDevice } from "@/api/newMonitor/device";

// IndexedDB数据库服务
const dbService = {
  DB_NAME: 'monitorVideoDB',
  DB_VERSION: 1,
  STORE_NAME: 'videos',
  db: null,

  // 打开数据库连接
  async openDB() {
    if (this.db) return this.db;
    
    return new Promise((resolve, reject) => {
      const request = indexedDB.open(this.DB_NAME, this.DB_VERSION);
      
      request.onerror = (event) => {
        console.error('IndexedDB打开失败:', event);
        reject(new Error('无法打开视频数据库'));
      };
      
      request.onsuccess = (event) => {
        this.db = event.target.result;
        console.log('IndexedDB连接成功');
        resolve(this.db);
      };
      
      request.onupgradeneeded = (event) => {
        const db = event.target.result;
        if (!db.objectStoreNames.contains(this.STORE_NAME)) {
          // 创建对象存储，使用视频文件名作为键
          const store = db.createObjectStore(this.STORE_NAME, { keyPath: 'fileName' });
          // 创建索引
          store.createIndex('deviceId', 'deviceId', { unique: false });
          store.createIndex('recordTime', 'recordTime', { unique: false });
          console.log('视频对象存储创建成功');
        }
      };
    });
  },
  
  // 根据文件名获取完整的视频数据
  async getVideoByFileName(fileName) {
    try {
      const db = await this.openDB();
      return new Promise((resolve, reject) => {
        const transaction = db.transaction([this.STORE_NAME], 'readonly');
        const store = transaction.objectStore(this.STORE_NAME);
        const request = store.get(fileName);
        
        request.onsuccess = (event) => {
          const video = event.target.result;
          if (video) {
            console.log('获取视频成功:', fileName);
            resolve(video);
          } else {
            console.warn('视频不存在:', fileName);
            resolve(null);
          }
        };
        
        request.onerror = (event) => {
          console.error('获取视频失败:', event);
          reject(new Error('获取视频失败'));
        };
      });
    } catch (error) {
      console.error('获取视频操作失败:', error);
      throw error;
    }
  },
  
  // 获取所有视频元数据(不包含视频Blob数据)
  async getAllVideoMetadata() {
    try {
      const db = await this.openDB();
      return new Promise((resolve, reject) => {
        const transaction = db.transaction([this.STORE_NAME], 'readonly');
        const store = transaction.objectStore(this.STORE_NAME);
        const request = store.getAll();
        
        request.onsuccess = (event) => {
          // 返回不包含视频Blob的元数据
          const videos = event.target.result.map(video => {
            // 解构，取出blobData之外的所有字段
            const { blobData, ...metadata } = video;
            return {
              ...metadata,
              source: 'indexeddb', // 标记数据来源
              status: '0' // 设置为正常状态
            };
          });
          resolve(videos);
        };
        
        request.onerror = (event) => {
          console.error('获取视频列表失败:', event);
          reject(new Error('获取视频列表失败'));
        };
      });
    } catch (error) {
      console.error('获取视频列表操作失败:', error);
      throw error;
    }
  },
  
  // 删除视频
  async deleteVideo(fileName) {
    try {
      const db = await this.openDB();
      return new Promise((resolve, reject) => {
        const transaction = db.transaction([this.STORE_NAME], 'readwrite');
        const store = transaction.objectStore(this.STORE_NAME);
        const request = store.delete(fileName);
        
        request.onsuccess = () => {
          console.log('视频删除成功:', fileName);
          resolve(true);
        };
        
        request.onerror = (event) => {
          console.error('删除视频失败:', event);
          reject(new Error('删除视频失败'));
        };
      });
    } catch (error) {
      console.error('删除视频操作失败:', error);
      throw error;
    }
  },
  
  // 检查数据库是否支持
  isSupported() {
    return window.indexedDB !== undefined;
  }
};

export default {
  name: "Video",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 监控视频表格数据
      videoList: [],
      // 设备列表
      deviceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示预览弹出层
      previewOpen: false,
      // 预览视频URL
      previewUrl: "",
      // 预览视频Blob
      previewBlob: null,
      // 视频加载状态
      videoLoading: false,
      // 时间范围
      timeRange: [],
      // 标签页选项
      activeTab: 'server',
      // 本地录像列表
      localRecordings: [],
      // 本地录像加载状态
      localLoading: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceId: null,
        fileName: null,
        status: null,
      },
      // 本地查询参数
      localQueryParams: {
        deviceName: null,
        fileName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        deviceId: [
          { required: true, message: "请选择所属设备", trigger: "change" }
        ],
        fileName: [
          { required: true, message: "请输入文件名称", trigger: "blur" }
        ],
        timeRange: [
          { required: true, message: "请选择视频时间段", trigger: "change" }
        ],
        filePath: [
          { required: true, message: "请输入存储路径", trigger: "blur" }
        ],
        fileSize: [
          { required: true, message: "请输入文件大小", trigger: "blur" }
        ],
      },
      // 是否支持IndexedDB
      isIndexedDBSupported: false,
      // 本地设备列表(去重)
      localDeviceList: []
    };
  },
  created() {
    this.getList();
    this.getDeviceList();
    
    // 检查IndexedDB支持
    this.isIndexedDBSupported = dbService.isSupported();
    if (!this.isIndexedDBSupported) {
      this.$message.info('您的浏览器不支持视频持久化存储，部分视频可能无法播放');
    } else {
      // 加载本地录像
      this.getLocalRecordings();
    }
  },
  beforeDestroy() {
    // 清理资源
    this.cleanupVideoResources();
  },
  computed: {
    // 根据查询条件筛选后的本地录像
    filteredLocalRecordings() {
      if (!this.localRecordings || this.localRecordings.length === 0) {
        return [];
      }
      
      return this.localRecordings.filter(item => {
        // 设备名称筛选
        if (this.localQueryParams.deviceName && 
            item.deviceName.indexOf(this.localQueryParams.deviceName) === -1) {
          return false;
        }
        
        // 文件名筛选
        if (this.localQueryParams.fileName && 
            item.fileName.indexOf(this.localQueryParams.fileName) === -1) {
          return false;
        }
        
        return true;
      });
    }
  },
  methods: {
    /** 查询监控视频列表 */
    getList() {
      this.loading = true;
      listVideo(this.queryParams).then(response => {
        // 处理数据，添加设备名称
        const rows = response.rows || [];
        rows.forEach(row => {
          const device = this.deviceList.find(d => d.deviceId == row.deviceId);
          row.deviceName = device ? device.deviceName : row.deviceId;
          row.source = 'server'; // 标记数据来源
        });
        this.videoList = rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取设备列表 */
    getDeviceList() {
      listDevice().then(response => {
        this.deviceList = response.rows || [];
      });
    },
    /** 获取本地录像列表 */
    async getLocalRecordings() {
      if (!this.isIndexedDBSupported) return;
      
      this.localLoading = true;
      try {
        // 从IndexedDB获取录像元数据
        const recordings = await dbService.getAllVideoMetadata();
        this.localRecordings = recordings;
        
        // 提取录像中的设备列表并去重
        this.updateLocalDeviceList();
        
        this.localLoading = false;
      } catch (error) {
        console.error('获取本地录像失败:', error);
        this.$message.error('获取本地录像失败: ' + error.message);
        this.localLoading = false;
      }
    },
    // 更新本地设备列表
    updateLocalDeviceList() {
      // 提取所有设备名称并去重
      const deviceNames = this.localRecordings
        .map(r => r.deviceName)
        .filter((v, i, a) => a.indexOf(v) === i);
      
      this.localDeviceList = deviceNames.map(name => ({
        deviceName: name
      }));
    },
    // 格式化文件大小
    formatFileSize(size) {
      if (!size) return "0 MB";
      
      // 如果已经是格式化后的字符串，直接返回
      if (typeof size === 'string' && size.includes(' ')) {
        return size;
      }
      
      const mb = size / (1024 * 1024);
      return mb.toFixed(2) + " MB";
    },
    // 处理时间范围变化
    handleTimeRangeChange(val) {
      if (val) {
        this.form.startTime = val[0];
        this.form.endTime = val[1];
      } else {
        this.form.startTime = null;
        this.form.endTime = null;
      }
    },
    // 预览视频
    async handlePreview(row) {
      this.videoLoading = true;
      this.previewOpen = true;
      this.previewUrl = null;
      this.cleanupVideoResources();
      
      try {
        // 根据来源选择不同的播放方式
        if (row.source === 'indexeddb' && this.isIndexedDBSupported) {
          // 从IndexedDB获取视频数据
          const indexedDBVideo = await dbService.getVideoByFileName(row.fileName);
          
          if (indexedDBVideo && indexedDBVideo.blobData) {
            console.log('从IndexedDB获取到视频数据');
            // 创建Blob URL
            this.previewBlob = indexedDBVideo.blobData;
            this.previewUrl = URL.createObjectURL(this.previewBlob);
            this.videoLoading = false;
            return;
          } else {
            this.$message.warning('无法获取视频数据，视频可能已被删除');
            this.videoLoading = false;
          }
        } else {
          // 首先尝试从IndexedDB中获取视频
          if (this.isIndexedDBSupported) {
            // 先尝试使用文件名查找
            let indexedDBVideo = null;
            
            // 尝试不同的可能的文件名格式
            const possibleNames = [
              row.fileName,
              `${row.fileName}.webm`,
              `${row.deviceName}_${row.fileName}.webm`
            ];
            
            for (const name of possibleNames) {
              indexedDBVideo = await dbService.getVideoByFileName(name);
              if (indexedDBVideo) break;
            }
            
            if (indexedDBVideo && indexedDBVideo.blobData) {
              console.log('从IndexedDB获取到视频数据');
              // 创建Blob URL
              this.previewBlob = indexedDBVideo.blobData;
              this.previewUrl = URL.createObjectURL(this.previewBlob);
              this.videoLoading = false;
              return;
            }
          }
          
          // 如果IndexedDB中没有找到，则使用服务器路径
          console.log('使用服务器路径');
          if (row.filePath) {
            this.previewUrl = `/video/${row.filePath}`;
            this.videoLoading = false;
          } else {
            this.$message.warning('未找到视频文件路径');
            this.videoLoading = false;
          }
        }
      } catch (error) {
        console.error('预览视频出错:', error);
        this.$message.error('预览视频失败: ' + error.message);
        this.videoLoading = false;
      }
    },
    // 清理视频资源
    cleanupVideoResources() {
      if (this.previewBlob && this.previewUrl) {
        URL.revokeObjectURL(this.previewUrl);
        this.previewBlob = null;
      }
      this.previewUrl = null;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.timeRange = [];
      this.form = {
        videoId: null,
        deviceId: null,
        filePath: null,
        fileName: null,
        startTime: null,
        endTime: null,
        fileSize: null,
        status: "0"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      if (this.activeTab === 'server') {
        this.queryParams.pageNum = 1;
        this.getList();
      }
    },
    /** 本地搜索按钮操作 */
    handleLocalQuery() {
      // 本地筛选不需要额外操作，通过计算属性自动过滤
    },
    /** 重置按钮操作 */
    resetQuery() {
      if (this.activeTab === 'server') {
        this.resetForm("queryForm");
        this.handleQuery();
      } else {
        this.localQueryParams = {
          deviceName: null,
          fileName: null
        };
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.videoId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 本地录像多选框选中数据
    handleLocalSelectionChange(selection) {
      // 本地录像的选中操作，暂时不需要特殊处理
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加监控视频";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // 只能修改服务器视频
      if (row.source === 'indexeddb') {
        this.$message.info('本地录像不支持修改操作');
        return;
      }
      
      this.reset();
      const videoId = row.videoId || this.ids
      getVideo(videoId).then(response => {
        this.form = response.data;
        if (this.form.startTime && this.form.endTime) {
          this.timeRange = [this.form.startTime, this.form.endTime];
        }
        this.open = true;
        this.title = "修改监控视频";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (!this.form.startTime || !this.form.endTime) {
            this.$message.error("请选择视频时间段");
            return;
          }
          
          if (this.form.videoId != null) {
            updateVideo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addVideo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      if (row.source === 'indexeddb') {
        // 删除本地录像
        this.$modal.confirm('是否确认删除录像"' + row.fileName + '"？此操作不可恢复！').then(async () => {
          try {
            // 从IndexedDB中删除
            await dbService.deleteVideo(row.fileName);
            
            // 从列表中移除
            const index = this.localRecordings.findIndex(r => r.fileName === row.fileName);
            if (index !== -1) {
              this.localRecordings.splice(index, 1);
            }
            
            // 更新本地设备列表
            this.updateLocalDeviceList();
            
            this.$modal.msgSuccess("删除成功");
          } catch (error) {
            console.error('删除本地录像失败:', error);
            this.$message.error('删除失败: ' + error.message);
          }
        }).catch(() => {});
      } else {
        // 删除服务器视频
        const videoIds = row.videoId || this.ids;
        this.$modal.confirm('是否确认删除监控视频编号为"' + videoIds + '"的数据项？').then(function() {
          return delVideo(videoIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('monitor/video/export', {
        ...this.queryParams
      }, `video_${new Date().getTime()}.xlsx`)
    },
    /** 下载本地录像 */
    async downloadLocalVideo(row) {
      try {
        // 从IndexedDB获取视频数据
        const video = await dbService.getVideoByFileName(row.fileName);
        
        if (!video || !video.blobData) {
          this.$message.error('无法获取视频数据，可能已被删除');
          return;
        }
        
        // 创建下载链接
        const url = URL.createObjectURL(video.blobData);
        const a = document.createElement('a');
        a.style.display = 'none';
        a.href = url;
        a.download = video.fileName;
        document.body.appendChild(a);
        a.click();
        
        // 清理资源
        setTimeout(() => {
          document.body.removeChild(a);
          URL.revokeObjectURL(url);
        }, 100);
        
        this.$message.success('开始下载录像');
      } catch (error) {
        console.error('下载录像失败:', error);
        this.$message.error('下载失败: ' + error.message);
      }
    },
    // 刷新所有数据
    refreshAll() {
      // 刷新服务器视频
      this.getList();
      
      // 刷新本地录像
      if (this.isIndexedDBSupported) {
        this.getLocalRecordings();
      }
    },
    // 切换标签页
    handleTabChange(tab) {
      this.activeTab = tab;
    },
    // 处理视频canplay事件
    handleVideoCanPlay() {
      console.log('视频已准备好播放');
      this.videoLoading = false;
      
      // 尝试自动播放
      const videoEl = this.$refs.previewVideo;
      if (videoEl) {
        videoEl.play().catch(err => {
          console.warn('自动播放失败:', err);
          // 部分浏览器限制自动播放，这是正常的
        });
      }
    },
    // 处理视频error事件
    handleVideoError(e) {
      const videoEl = this.$refs.previewVideo;
      console.error('视频加载错误:', videoEl.error);
      this.$message.error('视频加载失败: ' + (videoEl.error ? videoEl.error.message : '未知错误'));
      this.videoLoading = false;
    },
    // 关闭视频预览
    closeVideoPreview() {
      // 停止视频播放
      const videoEl = this.$refs.previewVideo;
      if (videoEl) {
        videoEl.pause();
        videoEl.currentTime = 0;
      }
      
      // 清理资源
      this.cleanupVideoResources();
      this.previewOpen = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.mb8 {
  margin-bottom: 12px;
}

:deep(.el-table) {
  .el-table__header-wrapper {
    th {
      background-color: #f5f7fa;
      color: #606266;
      font-weight: 500;
    }
  }
}

.el-tag {
  margin-right: 5px;
}

/* 数据库警告提示 */
.db-warning {
  background-color: #fdf6ec;
  padding: 10px 15px;
  border-radius: 4px;
  color: #e6a23c;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  
  i {
    font-size: 20px;
    margin-right: 10px;
  }
}

/* 标签页样式 */
:deep(.el-tabs--border-card) {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  
  .el-tabs__header {
    background-color: #f5f7fa;
  }
  
  .el-tabs__item.is-active {
    color: #409eff;
    font-weight: bold;
  }
  
  .el-tabs__content {
    padding: 15px;
  }
}

/* 对话框样式 */
.custom-dialog {
  .el-dialog__header {
    padding: 15px 20px;
    border-bottom: 1px solid #ebeef5;
  }
  
  .el-dialog__body {
    padding: 20px 25px;
  }
  
  .el-form-item__label {
    font-weight: 500;
  }
}

/* 视频预览对话框 */
.preview-dialog {
  .video-container {
    width: 100%;
    min-height: 400px;
    background: #000;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
  }

  .video-player {
    width: 100%;
    max-height: 400px;
    object-fit: contain;
  }

  .no-video {
    text-align: center;
    color: #909399;

    i {
      font-size: 48px;
      margin-bottom: 16px;
    }

    p {
      margin: 0 0 8px;
      font-size: 14px;
    }
    
    .video-help-text {
      font-size: 12px;
      color: #c0c4cc;
    }
  }
}

/* 自定义样式，针对特殊情况的处理 */
.empty-data {
  text-align: center;
  color: #909399;
  padding: 30px 0;
  
  i {
    font-size: 48px;
    margin-bottom: 15px;
  }
  
  p {
    font-size: 14px;
    margin: 0;
  }
}

/* 当屏幕较小时，优化表单布局 */
@media (max-width: 768px) {
  :deep(.el-form--inline .el-form-item) {
    display: block;
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  :deep(.el-input), 
  :deep(.el-select) {
    width: 100% !important;
  }
}
</style>
